// pages/saleform/saleform.js
const app = getApp();
const date = new Date()
const years = []
const months = []
const days = []
//const user = JSON.parse(wx.getStorageSync("user"));
const base_url = app.globalData.base_url;
const util = require('../../utils/util.js');

for (let i = 1990; i <= date.getFullYear(); i++) {
  years.push(i)
}

for (let i = 1; i <= 12; i++) {
  months.push(i)
}

for (let i = 1; i <= 31; i++) {
  days.push(i)
}


Page({

  /**
   * 页面的初始数据
   */
  data: {
    hei:0,
    price:{
      array: [
        ["1万", "2万", "3万", "4万", "5万", "6万", "7万", "8万", "9万","10万"],
        ["0千", "1千", "2千", "3千", "4千", "5千", "6千", "7千", "8千","9千"], 
      ],
      value:[0,0]
    },
    earnest:{
      array:["1千", "2千", "3千", "4千", "5千", "6千", "7千", "8千", "9千"],
      value:0
    },
    id:'',//编辑时id
    pickerFlag: false,//时间选择器
    sexActive: -1,
    years: years,
    year: date.getFullYear(),
    months: months,
    month: 2,
    days: days,
    day: 2,
    value: [9999, 1, 1],
    imgPaths:[],
    videoPaths:[],
    titleLen: 0,//标题长度
    bj:false,
    formData: {
      title:'',
      content:'',
      price:'',
      earnest:'',
      dog_sex:-1,
      dog_brithday:'',
      hair_color:'',
      father_studbook:'',
      mother_studbook:'',
      father_chip_num:'',
      mother_chip_num:'',
      insect_record:[],
      vaccine_record:[],
      img_url:[],
      video_url:[]
    },
    recFlag: -1,
    bossArray:{
      insectArr: {    //驱虫记录
        list: [       //驱虫记录数组
          {
            "switch": true,  //加 开关 是否显示
            "time": '',      //时间
            "name": ''
          }
        ],
        index: 0
      },
      vaccineArr: {   //疫苗记录
        list: [       //疫苗记录数组
          {
            "switch": true,  //加 开关 是否显示
            "time": '',      //时间
            "name": ''
          }
        ],
        index: 0
      },//疫苗记录,
      selected:0    //0 代表驱虫记录  1代表疫苗记录
    },
   //驱虫记录
    videolist:[],     //上传视频路径
    videosee:[]       //视频预览路径
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '填写售卖信息'
    })
    if(options.id){
      this.setData({
        id: options.id,
        bj:true
      })
      this.init();
    }
    wx.getSystemInfo({
      success: res => {
        let windowHeight = (res.windowHeight * (750 / res.windowWidth));
        this.setData({
          hei: windowHeight - 148
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  bindPickerChange(e){
    let index = e.detail.value;
    let priceArr = this.data.price.array;
   
    let price = parseInt(priceArr[0][index[0]]) * 10000 + parseInt(priceArr[1][index[1]])*1000
    this.setData({
      'price.value': index,
      'formData.price':price
    })
  },
  QPickerChange(e){
    let priceArr = this.data.earnest.array;
    let index=parseFloat(e.detail.value)
    this.setData({
      'earnest.value': index,
      'formData.earnest': parseInt(priceArr[index])*1000
    })
  },
  init(){
    wx.showLoading({
      title: '加载中',
      success:()=>{
        wx.request({
          url: base_url + '/Post/detail',
          data: {
            'user_token': JSON.parse(wx.getStorageSync("user")).user_token,
            'id': this.data.id
          },
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: res => {
            wx.hideLoading();
            if (res.data.success == '1' && res.data.data) {
              let videosee = [], videolist=[];
              if (res.data.data.video_img){
                videosee.push(res.data.data.video_img)
              }else{
                videosee=[]
              }
              this.setData({
                'formData.title': res.data.data.title,
                'formData.price': res.data.data.price,
                'formData.earnest': res.data.data.earnest,
                'formData.content': res.data.data.content,
                'formData.img_url': res.data.data.img_list,
                'imgPaths': res.data.data.img_list,
                'formData.video_url': videosee,
                'formData.dog_sex': res.data.data.dog_sex,
                'formData.dog_brithday': res.data.data.dog_brithday,
                'formData.hair_color': res.data.data.hair_color,
                'formData.father_studbook': res.data.data.father_studbook,
                'formData.mother_studbook': res.data.data.mother_studbook,
                'formData.father_chip_num': res.data.data.father_chip_num,
                'formData.mother_chip_num': res.data.data.mother_chip_num,
                'formData.insect_record': res.data.data.insect_record,
                'formData.vaccine_record': res.data.data.vaccine_record,
                videosee:videosee,
                videolist: videosee
              })
              let insect_record = res.data.data.insect_record;
                let insectArr = this.data.bossArray.insectArr.list
                for (let i = 0; i < insect_record.length;i++){
                  insect_record[i].switch = false;
                  if (i == insect_record.length-1 && i<2){
                    insect_record[i].switch = true;
                  }
                  insectArr[i] = insect_record[i]
                }
                for (let val of insectArr){
                  val.time=val.date
                }
                this.setData({
                  'bossArray.insectArr.list': insectArr
                })
                let vaccine_record = res.data.data.vaccine_record;
                let vaccineArr = this.data.bossArray.vaccineArr.list
                for (let i = 0; i < vaccine_record.length; i++) {
                  vaccine_record[i].switch = false;
                  if (i == vaccine_record.length - 1 && i < 2) {
                    vaccine_record[i].switch = true;
                  }
                  vaccineArr[i] = vaccine_record[i]
                }
                for (let val of vaccineArr) {
                  val.time = val.date
                }
                this.setData({
                  'bossArray.vaccineArr.list': vaccineArr
                })
            }
          }
        })
      }
    })
  },
  userNameInput(e) {
    let index = e.currentTarget.dataset.index;
    let vtype = e.currentTarget.dataset.vtype;
    if (vtype == 'insect_record') {
      let label = 'bossArray.insectArr.list[' + index + '].name';
      this.setData({
        [label]: e.detail.value
      })
      
    } else {
      let label = 'bossArray.vaccineArr.list[' + index + '].name';
      this.setData({
        [label]: e.detail.value
      })
    }
  },
  add(event) {   //添加驱虫记录 + 按钮   时间选择时把index赋值给弹窗 然后选择完时间给对应array index 的 time
    let index = event.currentTarget.dataset.index; //数组索引;
    let vtype = event.currentTarget.dataset.vtype;
    let neww,arr;
    if (vtype == 'insect_record'){
      this.setData({
        'bossArray.selected':0
      })
      neww = this.data.bossArray.insectArr;     //获取数组
      arr = "bossArray.insectArr";
    }else{
      this.setData({
        'bossArray.selected':1
      })
      neww = this.data.bossArray.vaccineArr;  
      arr = "bossArray.vaccineArr";
    }

    if (!neww.list[index].name || !neww.list[index].time) { //判断是否填写记录 和 选择时间
      wx.showToast({
        title: '请输入时间和记录',
        icon: 'none',       //傻逼小程序
        duration: 2000
      })
      return false;
    } else {
      neww.index=index;
      let bool;
      neww.list[index].switch = false;      //关闭添加按钮
      neww.list.push({            //新增空数据
        "switch": index==1?false:true,
        "time": null,
        "name": null
      })
      this.setData({
        [arr]: neww
      })
    }
  },

  save () {//时间选择器确认
    let index;    //索引
    let type = this.data.bossArray.selected;    //0  1
    let Brr=new Array(),Crr;
    if(type==0){
      index = this.data.bossArray.insectArr.index;
      Brr = this.data.bossArray.insectArr;
      Crr = "bossArray.insectArr.list"
    }else if(type==1){
      index = this.data.bossArray.vaccineArr.index;
      Brr = this.data.bossArray.vaccineArr;
      Crr = "bossArray.vaccineArr.list"
    }else{  //
      console.log(util.zero(this.data.year) + '-' + util.zero(this.data.month) + '-' + util.zero(this.data.day))
      this.setData({
        'formData.dog_brithday': util.zero(this.data.year) + '-' + util.zero(this.data.month) + '-' + util.zero(this.data.day),
        'pickerFlag': false,
      })
      return 
    }
    Brr.list[index].time = util.zero(this.data.year) + '-' + util.zero(this.data.month) + '-' + util.zero(this.data.day)
    this.setData({
      [Crr]: Brr.list,
      pickerFlag: false
    })
  },
  clear: function () {//关闭选择器
    this.setData({ pickerFlag: false })
    this.setData({
      recFlag: -1,
    })
  },
  del(e) {
    let types = e.currentTarget.dataset.type;
    //let Arr = types == 0 ? this.data.img_url : this.data.videolist
    let index = types == 0 ? e.currentTarget.dataset.ind : 0
    if (types == 0) {
      let Arr = this.data.formData.img_url, imgPaths = this.data.imgPaths;
      Arr.splice(index, 1)
      imgPaths.splice(index, 1)
      this.setData({
        'formData.img_url': Arr,
        imgPaths: imgPaths
      })
    } else {
      this.setData({
        videolist: [],
        videosee: []
      })
    }

  },
  pickerTime: function (e) {
    let index = e.currentTarget.dataset.index;
    let time;
    if (e.currentTarget.dataset.vtype == 'insect_record') {
      this.setData({
        recFlag: 0,
      })
      time = this.data.bossArray.insectArr.list[index].time;
      this.setData({
        "bossArray.selected": 0,
        "bossArray.insectArr.index":index,
      //  "year": this.data.bossArray.insectArr.list[index].time.splite("-")[0]
      })
    } else if (e.currentTarget.dataset.vtype == 'vaccine_record') {
      this.setData({
        recFlag: 1,
      })
      time = this.data.bossArray.vaccineArr.list[index].time;
      this.setData({
        "bossArray.selected":1,
        "bossArray.vaccineArr.index": index,
      })
    }else{
      this.setData({
        "bossArray.selected":null
      })
    }
    if (time) {
      let yearIndex, monthIndex, daysindex;
      for (let [index, val] of this.data.years.entries()) {
        if (val == time.split("-")[0]) {
          yearIndex = index
        }
      }
      for (let [index, val] of this.data.months.entries()) {
        if (val == time.split("-")[1]) {
          monthIndex = index
        }
      }
      for (let [index, val] of this.data.days.entries()) {
        if (val == time.split("-")[2]) {
          daysindex = index
        }
      }
      this.setData({
        "value": [yearIndex, monthIndex, daysindex],
      })
    }
    this.setData({
      pickerFlag: true
    })
  },
  prevent: function () { },//阻止滚动
  bindChange: function (e) {//时间选择器
    const val = e.detail.value
    this.setData({
      year: this.data.years[val[0]],
      month: this.data.months[val[1]],
      day: this.data.days[val[2]]
    })
  },
  getTitle: function (e) {
    let label = 'formData.title';
    this.setData({
      titleLen: e.detail.cursor,
      [label]: e.detail.value
    })
  },
  getData: function (e) {
    let vtype = e.currentTarget.dataset.vtype;
    let label = 'formData.' + vtype;
    vtype == 'dog_sex' && this.setData({ sexActive: e.currentTarget.dataset.value })
    this.setData({
      [label]: e.currentTarget.dataset.value || e.detail.value
    })
  },
  addpic() {
    // let newArr;
    // if (this.data.videolist.length==0){
    //   newArr=["照片","视频"]
    // }else{
    //   newArr=["照片"]
    // }
    let newArr = ['图片', '视频'];
    if (this.data.videolist.length > 0) {
      newArr = [''];
    }
    if (this.data.imgPaths.length > 0) {
      newArr = ['图片']
    }
    wx.showActionSheet({
      itemList: newArr,
      success: res => {
        if(res.tapIndex == 0){
          wx.chooseImage({
            count: 9,
            sourceType: ['album'],
            success: res => {
              wx.showLoading({
                title: '正在上传图片',
                success:()=>{
                  let arr = 'imgPaths[' + this.data.imgPaths.length + ']';
                  if (this.data.imgPaths.length > 0) {
                    var i = this.data.imgPaths.length;
                    this.setData({
                      imgPaths: this.data.imgPaths.concat(res.tempFilePaths)
                    })
                  } else {
                    var i = 0;
                    this.setData({
                      imgPaths: res.tempFilePaths
                    });
                  }
                  let callback = () => {
                    wx.uploadFile({
                      url: base_url + '/File/uploadImage',
                      name: 'uploads',
                      filePath: this.data.imgPaths[i],
                      header: {
                        'content-type': 'multipart/form-data'
                      },
                      success: res => {

                        let data = JSON.parse(res.data);
                        if (data.success == '1') {
                            // let img_url = this.data.formData.img_url.map(v=>{
                            //   return v.replace(/http:\/\/118.126.92.149/g, '')
                            // })
                          let img_url = this.data.formData.img_url;
                          // let newUrl = [];
                          img_url.push(data.data.path)
                          this.setData({
                            'formData.img_url': img_url
                          })
                          i++;//上传张数
                          if (i == this.data.imgPaths.length) {//上传结束
                            wx.hideLoading()
                            wx.showToast({
                              title: '上传成功',
                              mask: true,
                              icon: 'success',
                              duration: 2000
                            })
                          } else {
                            callback()
                          }
                        }
                      }
                    })
                  }
                  callback()
                }
              })
              

            },
            fail:res =>{
              wx.showToast({
                title: '取消上传',
                icon:'none',
                duration:2000
              })
            }
          })
        }else{
          let videolist=this.data.videolist,
              videosee=this.data.videosee;
          wx.chooseVideo({
            sourceType: ['album'],
            maxDuration: 60,
            camera: 'back',
            success: res=> {
              wx.showLoading({
                title: '上传中',
              })
              wx.uploadFile({
                url: base_url + '/File/uploadVideo',
                name: 'uploads',
                filePath: res.tempFilePath,
                header: {
                  'content-type': 'multipart/form-data'
                },
                success: data => {
                  let ndata=JSON.parse(data.data);
                  wx.hideLoading();
                  wx.showToast({
                    title: '上传成功',
                    mask: true,
                    icon: 'success',
                    duration: 2000
                  })
                  videolist.push(ndata.data.path)
                  videosee.push(ndata.data.video_img)
                  this.setData({
                    videolist:videolist,
                    videosee: videosee,
                    "formData.video_url": videolist
                  })
                }
              })
            }
          })
        }
      },
      fail: function (res) {
        console.log(res.errMsg)
      }
    })  
    
  },
  confirm:function(){
    if(this.data.formData.title == ''){
      wx.showToast({
        title: '标题不能为空',
        icon: 'none',
        duration: 2000
      })
      return false
    } else if (this.data.formData.price == ''){
      wx.showToast({
        title: '售价不能为空',
        icon: 'none',
        duration: 2000
      })
      return false
    } else if (this.data.formData.earnest == ''){
      wx.showToast({
        title: '定金不能为空',
        icon: 'none',
        duration: 2000
      })
      return false
    }else{
    for (let val of this.data.bossArray.insectArr.list){
      if (!val.time || !val.name){
        wx.showToast({
          title: '请填写完整记录',
          icon: 'none',
          duration: 2000
        })
        return false
      }
    }
    for (let val of this.data.bossArray.vaccineArr.list) {
      if (!val.time || !val.name) {
        wx.showToast({
          title: '请填写完整记录',
          icon: 'none',
          duration: 2000
        })
        return false
      }
    }
    let insect = [];
    for (let i = 0; i < this.data.bossArray.insectArr.list.length;i++){
      insect.push(this.data.bossArray.insectArr.list[i].time + '#' + this.data.bossArray.insectArr.list[i].name);
    }
    let insect_record = insect.join('&');

    let vaccine = [];
    for (let i = 0; i < this.data.bossArray.vaccineArr.list.length; i++) {
      vaccine.push(this.data.bossArray.vaccineArr.list[i].time + '#' + this.data.bossArray.vaccineArr.list[i].name);
    }
    let vaccine_record = vaccine.join('&');
    this.setData({
      'formData.insect_record': insect_record,
      'formData.vaccine_record': vaccine_record
    })
    if(typeof(this.data.formData.img_url) != 'string'){
      let img_url = this.data.formData.img_url.map(v => {
        return v.replace(/https:\/\/m.frenchiesplus.com/g, '')
      })
      this.setData({
        'formData.img_url':img_url.join(',')
      })
    }
     if (this.data.formData.video_url.length > 0  && this.data.id){
        let url = this.data.formData.video_url[0].replace(/https:\/\/m.frenchiesplus.com/g, '')
        this.setData({
          'formData.video_url': url
        })
      }

    wx.showModal({
      title: '提示',
      content: '确认提交售卖帖子？',
      success: res => {
        if(res.confirm){
          wx.showLoading({
            success: (res) => {
              let data = this.data.formData;
              data.user_token = JSON.parse(wx.getStorageSync("user")).user_token;
              if (this.data.id != '') {
                data.id = this.data.id;
                var url = base_url + '/Post/editSale';
              } else {
                var url = base_url + '/Post/addSale';
              }
              wx.request({
                url: url,
                data: data,
                method: 'POST',
                header: {
                  'content-type': 'application/x-www-form-urlencoded'
                },
                success: res => {
                  wx.hideLoading()
                  if (res.data.success == '1') {
                    wx.showToast({
                      title: '发布成功',
                      icon: 'success',
                      duration: 2000
                    })
                    wx.redirectTo({
                      url: '/pages/index/index',
                    });
                  } else {
                    wx.showToast({
                      title: res.data.msg,
                      icon: 'none',
                      duration: 2000
                    })
                  }

                }
              })
            }
          })
        }else if(res.cancel){
          wx.showToast({
            title: '已取消提交',
            icon: 'none',
            duration: 2000
          })
        }
       
      }
    }) 
    } 
  },
})